package com.storm

import java.util.Collections

fun main() {

    val str: String? = null
    println(str.isNullOrBlank())

    val sudoku: Array<IntArray> = arrayOf(
        intArrayOf(0, 0, 1, 0, 5, 0),
        intArrayOf(2, 0, 0, 1, 0, 0),
        intArrayOf(0, 6, 0, 0, 0, 2),
        intArrayOf(5, 0, 0, 0, 3, 0),
        intArrayOf(0, 0, 6, 0, 0, 5),
        intArrayOf(0, 1, 0, 3, 0, 0),
    )

    val result: Array<IntArray> = sudoku.map {
        it.copyOf()
    }.toTypedArray()

    val maxC = sudoku.size - 1
    val maxR = sudoku[0].size - 1
    val rlength = sudoku[0].size


    var r = 0
    var c = 0
    var backNow = false
    //需要进行处理
    out@ while (c <= maxC && r <= maxR) {
        if (sudoku[r][c] == 0) {
            backNow = false
            for (value in result[r][c]..rlength) {
                if (value == 0) {
                    continue
                }
                if (dealOne(r, c, value, result,rlength)) {
                    break
                } else {
                    if (value == rlength) {
                        backNow = true
                        result[r][c] = 0
                        if (c > 0) {
                            c--
                        } else {
                            r--
                            c = maxC
                        }
                        continue@out
                    }
                }

            }
        } else {
            if (backNow) {
                if (c > 0) {
                    c--
                } else {
                    r--
                    c = maxC
                }
                continue@out
            }
        }
        if (c < maxC) {
            c++
        } else {
            r++
            c = 0
        }
    }

    for (ints in result) {
        ints.forEach { print("$it ") }
        println()
    }

}

private fun dealOne(r: Int, c: Int, value: Int, result: Array<IntArray>,numLength:Int): Boolean {
    //正方形长和宽一样
    //长度(列长)
    val cl = 3
    //宽度(行长)
    val rl = 2

    //长方块范围划分
    /*
        ra/ca---------ra/cb
        |                 |
        |                 |
        |                 |
        rb/ca---------rb/cb
     */
    val ra = r / rl * rl
    val rb = ra + rl - 1

    val ca = c / cl * cl
    val cb = ca + cl - 1

    //行判断
    for (i in 0 until numLength) {
        if (value == result[r][i]) {
            return false
        }
    }
    //列判断
    for (i in 0 until numLength) {
        if (value == result[i][c]) {
            return false
        }
    }
    //矩形判断
    for (i in ra..rb) {
        for (j in ca..cb) {
            if (value == result[i][j]) {
                return false
            }
        }
    }
    result[r][c] = value
    return true
}

